﻿// Copyright (c) 2008, 3G.cn
// $Author: Moweiqiang $
// $Date: 09-03-06 16:48 $
// $Revision: 4 $
// $NoKeywords: $
namespace Jiubang.Wap {
	using System;
	using System.Drawing.Imaging;
	using System.IO;
	using System.Web;
	using System.Web.UI.WebControls;
	using Image=System.Drawing.Image;

	/// <summary>
	/// ImageHelper 的摘要说明
	/// </summary>
	public class ImageHelper {
		private static readonly string[] defaultAllowedSubfixes;
		private readonly string[] allowedSubfixes;
		private int maxSize = 300*1024;

		static ImageHelper() { defaultAllowedSubfixes = new[] {"gif", "jpg", "png", "bmp"}; }

		/// <param name="allowedSubfixes">允许上传的文件后缀</param>
		public ImageHelper(params string[] allowedSubfixes) {
			if (allowedSubfixes != null && allowedSubfixes.Length > 0)
				this.allowedSubfixes = allowedSubfixes;
			else
				this.allowedSubfixes = defaultAllowedSubfixes;
		}

		/// <summary>
		/// 设置或获取当前实例允许上传的最大值
		/// </summary>
		public int MaxSize {
			get { return maxSize; }
			set { maxSize = value; }
		}

		/// <summary>
		/// 允许上传的文件后缀枚举
		/// </summary>
		public string[] AllowedSubfixes {
			get { return allowedSubfixes; }
		}

		/// <summary>
		/// 上传文件到指定目录，并返回保存后的地址(不带savePath)
		/// </summary>
		/// <param name="postedFile"></param>
		/// <param name="savePath"></param>
		/// <returns></returns>
		public string GetUpload(HttpPostedFile postedFile, string savePath) {
			if (postedFile == null)
				throw new ArgumentNullException("postedFile");
			if (string.IsNullOrEmpty(savePath))
				throw new ArgumentNullException("savePath");

			string extension = Path.GetExtension(postedFile.FileName);
			if (postedFile.ContentLength > MaxSize)
				return null;
			if (!isValidExtension(extension))
				return null;

			string filepath = GetNewFileName(extension);
			postedFile.SaveAs(savePath + filepath);
			return filepath;
		}
		/// <summary>
		/// 创建根据时间命名的新文件名
		/// </summary>
		/// <param name="extension"></param>
		/// <returns></returns>
		public static string GetNewFileName(string extension) { return DateTime.Now.ToString("yy/M/d/HHmmssff") + SqlCache.Random.Next(byte.MaxValue).ToString("h") + extension; }

		/// <summary>
		/// 返回上传图片的宽高
		/// </summary>
		/// <param name="fu">FileUpload实例</param>
		/// <param name="width">返回的宽度</param>
		/// <param name="height">返回的高度</param>
		/// <returns>非图片时返回否</returns>
		public static bool GetUploadImageSize(FileUpload fu, out int width, out int height) {
			Image image;
			try {
				using (image = Image.FromStream(fu.FileContent)) {
					width = image.Width;
					height = image.Height;
				}
				return true;
			} catch {
				width = 0;
				height = 0;
				return false;
			}
		}

		/// <summary>
		/// 返回指定文件的宽高
		/// </summary>
		/// <param name="filefullname"></param>
		/// <param name="width"></param>
		/// <param name="height"></param>
		/// <returns>非图片时返回否</returns>
		public static bool GetUploadImageSize(string filefullname, out int width, out int height) {
			Image image;
			try {
				using (image = Image.FromFile(filefullname)) {
					width = image.Width;
					height = image.Height;
				}
				return true;
			} catch {
				width = 0;
				height = 0;
				return false;
			}
		}


		/// <summary>
		/// 生成缩略图，并保存在指定的位置
		/// </summary>
		/// <param name="OriginFile">原文件地址</param>
		/// <param name="SavePath">缩略图保存路径</param>
		/// <returns></returns>
		public static bool ToThumbnail(string OriginFile, string SavePath) { return ToThumbnail(OriginFile, SavePath, 120); }

		/// <summary>
		/// 生成缩略图，并保存在指定的位置
		/// </summary>
		/// <param name="OriginFile">原文件地址</param>
		/// <param name="SavePath">缩略图保存路径</param>
		/// <param name="width">缩略图宽度(px)</param>
		/// <returns></returns>
		public static bool ToThumbnail(string OriginFile, string SavePath, int width) {
			try {
				using (Image image = Image.FromFile(OriginFile)) {
					double proportion = ((double) width)/image.Width;
					int height = (int) Math.Ceiling(image.Height*proportion);
					using (Image thumbnail = image.GetThumbnailImage(width, height, null, IntPtr.Zero))
						thumbnail.Save(SavePath, ImageFormat.Jpeg);
				}
				return true;
			} catch {
				return false;
			}
		}

		/// <summary>
		/// 验证文件是否符合上传要求。
		/// 如果web.config没有定义AppSettings["allowSubfix"]或为空，则使用默认值gif|jpg|png|bmp
		/// </summary>
		/// <param name="postFileName">文件名可带路径</param>
		/// <returns></returns>
		public bool IsValidFile(string postFileName) {
			string fileSubfix = Path.GetExtension(postFileName);
			return isValidExtension(fileSubfix);
		}

		/// <summary>
		/// 验证文件名后缀是否被允许
		/// 如果web.config没有定义AppSettings["allowSubfix"]或为空，则使用默认值gif|jpg|png|bmp
		/// </summary>
		/// <param name="fileSubfix">带.的文件后缀，如.aspx</param>
		/// <returns></returns>
		public bool isValidExtension(string fileSubfix) {
			fileSubfix = fileSubfix.Remove(0,1);
			foreach (string subfix in AllowedSubfixes)
				if (fileSubfix == subfix)
					return true;
			return false;
		}
	}
}